﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using System.Data;
using DevExpress.Web.Mvc;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 上级考核栏目定义
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]    
    public class ChkInfoClsController : AdminBaseController
    {
        //
        // GET: /Admin/ChkInfoCls/
        /// <summary>
        /// 上级考核栏目定义首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_ChkInfoCls", Order = 1)]
        [LogPageActionFilter("上级考核栏目定义", Order = 2)]
        public ActionResult Index(string year)
        {
            if (year == null || year == "")
            {
                year = DateTime.Now.Year.ToString();
            }
            BLL.ChkInfoCls ChkInfoClsBLL = new BLL.ChkInfoCls();
            DataSet ds = ChkInfoClsBLL.GetYeat(Common.GlobalConstant.ENTITYNO);
            if (ds.Tables[0].Rows.Count == 0)
            {
                ViewData["minyear"] = year;
                ViewData["maxyear"] = year;

            }
            else
            {
                ViewData["maxyear"] = ds.Tables[0].AsEnumerable().Select(t => t.Field<decimal>("FYear")).Max();
                ViewData["minyear"] = ds.Tables[0].AsEnumerable().Select(t => t.Field<decimal>("FYear")).Min();
            }


            ViewData["dqyear"] = year;

            return View();
        }


        /// <summary>
        /// 树
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult ChkInfoClsTree(string year) {

           // string year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);                  
            TreeModelList treeModelList = new TreeModelList();

            TreeItemModel treeParentItemModel = new TreeItemModel(null)
            {
                Id = "ChkInfoClsAllList?id=-1&year=" + year,
                Name = "所有栏目",
                ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

            };

            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();
            DataSet ds = bll.GetList("FYear =" + year + " and FEntityNo='" + GlobalConstant.ENTITYNO + "'");
            if(ds.Tables.Count != 0)
            {
                DataTable dt = ds.Tables[0];
                DataRow[] dr = dt.Select("FPreInfoClsNo is Null or FPreInfoClsNo=''");
                for (int i = 0; i < dr.Length; i++ )
                {
                    TreeItemModel treeSonItemModel = new TreeItemModel(treeParentItemModel)
                    {
                        Id = "ChkInfoClsDetail?id=" + dr[i]["FInfoClsNo"].ToString() + "&year=" + year,
                        Name = dr[i]["FInfoClsName"].ToString(),
                        ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                    };
                    GetChildNode(treeSonItemModel, dr[i]["FInfoClsNo"].ToString(), dt, year);
                }
            }

            treeModelList.Add(treeParentItemModel);
            return View(treeModelList);
        
        }

        /// <summary>
        /// 循环得到树节点
        /// </summary>
        /// <param name="treeSonItemModel">子节点</param>
        /// <param name="fInfoClsNo">栏目编号</param>
        /// <param name="dt">列表</param>
        private void GetChildNode(TreeItemModel treeSonItemModel, string fInfoClsNo, DataTable dt,string year)
        {
            //string year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            
            DataRow[] dr = dt.Select("FPreInfoClsNo='" + fInfoClsNo + "'");
            for (int i = 0; i < dr.Length; i++)
            {
                TreeItemModel treeItemModel = new TreeItemModel(treeSonItemModel)
                {
                    Id = "ChkInfoClsDetail?id=" + dr[i]["FInfoClsNo"].ToString() + "&year=" + year,
                    Name = dr[i]["FInfoClsName"].ToString(),
                    ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                };
                GetChildNode(treeItemModel, dr[i]["FInfoClsNo"].ToString(), dt, year);

            }

        }


        /// <summary>
        /// 右边的页面
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult ChkInfoClsAllList(string year)
        {
            int pageIndex = 1;
           

            //string year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);

            List<Model.ChkInfoCls> chkInfoClsList = new List<Model.ChkInfoCls>();
            chkInfoClsList = GetChkInfoClsList(pageIndex, year);
          
            ViewData["year"] = year;

            return View(chkInfoClsList);
           
        }

        /// <summary>
        /// 页面列表
        /// </summary>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageCount">当前页</param>
        /// <param name="pageRowSize">行数</param>
        /// <returns>集合</returns>
        private List<Model.ChkInfoCls> GetChkInfoClsList(int pageIndex,string year, int pageCount = 0, int pageRowSize = 0)
        {
            BLL.ChkInfoCls chkInfoClsBll = new BLL.ChkInfoCls();


            string where = "FEntityNo='" + GlobalConstant.ENTITYNO + "'" + "and FYear='" + year + "'";

            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("t_chkInfoCls", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FYear", 0, out total);

            List<Model.ChkInfoCls> chkInfoClsAllList = new List<Model.ChkInfoCls>();
            List<Model.ChkInfoCls> chkInfoClsList = chkInfoClsBll.DataTableToListChkInfoCls(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                chkInfoClsAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (chkInfoClsList.Count > i)
                {
                    chkInfoClsAllList[((pageIndex - 1) * pageRowSize) + i] = chkInfoClsList[i];
                }
            }

            return chkInfoClsAllList;
        }

        /// <summary>
        /// 用于刷新页面
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult ChkInfoClsAllListPartial() 
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string year = Request.Params["year"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.ChkInfoCls> chkInfoClsAllList = GetChkInfoClsList(pageIndex, year, pageRowSize);


            return PartialView("ChkInfoClsAllListPartial", chkInfoClsAllList);
        
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult ChkInfoClsAdd(string year)
        {
            ViewData["year"] = year;
            Model.ChkInfoCls chkInfoCls = new Model.ChkInfoCls();

            //string year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            string preid = Request["preid"];

            if (year != null && year != "" && preid != null && preid != "")
            {
                chkInfoCls.FYear = decimal.Parse(year);
                chkInfoCls.FPreInfoClsNo = preid;
                chkInfoCls.FChkType = "1";
                chkInfoCls.FisExamine = "N";
                chkInfoCls.FStdScore = 0;

            }
            else if (year != null && year != "" && (preid == null || preid == ""))
            {
                chkInfoCls.FYear = decimal.Parse(year);
                chkInfoCls.FPreInfoClsNo = "无";
                chkInfoCls.FChkType = "1";
                chkInfoCls.FisExamine = "N";
                chkInfoCls.FStdScore = 0;
            }


            return View(chkInfoCls);
        }

        /// <summary>
        /// 判断
        /// </summary>
        /// <param name="infoClsNo">栏目编号</param>
        /// <returns>Y：存在，N：不存在</returns>
        public string ExistsChkInfoCls(string infoClsNo,string  year)
        {
            string str = string.Empty;
            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();
            if (bll.Exists(decimal.Parse(year), infoClsNo, GlobalConstant.ENTITYNO))
            {
                str = "Y";
            }
            else
            {
                str = "N";
            }


            return str;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="item">一个model对象</param>
        /// <returns>视图</returns>
        public ActionResult SaveAll(Model.ChkInfoCls item) 
        {
            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();

            item.FYear = decimal.Parse(Fetch.Post("hidyear"));

            item.FChkType = DropDownEditExtension.GetValue<string>("FChkType");
            item.FInfoClsName = Fetch.Post("FInfoClsName").Trim();
            item.FInfoClsNo = Fetch.Post("FInfoClsNo").Trim();
            item.FisExamine = DropDownEditExtension.GetValue<string>("FisExamine");
            item.FStdScore = Convert.ToDecimal(Fetch.Post("FStdScore").Trim());
            item.FEntityNo = GlobalConstant.ENTITYNO;

            string fPreInfoClsNo = Fetch.Post("hidPreInfoClsNo").Trim();

            if (fPreInfoClsNo == "无")
            {
                item.FPreInfoClsNo = "";
            }
            else
            {
                item.FPreInfoClsNo = Fetch.Post("hidPreInfoClsNo").Trim();

            }

            bll.Add(item);
            Response.Write("<script>alert('操作成功！');parent.location.href='" + Url.Action("Index", "ChkInfoCls") + "'</script>");
            Response.Flush();
            Response.End();

            return View("ChkInfoClsAllList", item);
        }


        /// <summary>
        /// 给页面赋值
        /// </summary>
        /// <param name="year">年度</param>
        /// <param name="id">编号</param>
        /// <returns>视图</returns>
        public ActionResult ChkInfoClsDetail(string year, string id)
        {
            Model.ChkInfoCls chkInfoClsModel = new Model.ChkInfoCls();
            //year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            ViewData["year"] = year;

            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();

            Model.ChkInfoCls item = bll.GetModel(Convert.ToDecimal(year), id, GlobalConstant.ENTITYNO);
            if(item != null){
                chkInfoClsModel.FYear = item.FYear;
                chkInfoClsModel.FInfoClsNo = item.FInfoClsNo;
                chkInfoClsModel.FPreInfoClsNo = item.FPreInfoClsNo;
                chkInfoClsModel.FInfoClsName = item.FInfoClsName;
                chkInfoClsModel.FStdScore = item.FStdScore;
                chkInfoClsModel.FChkType = item.FChkType == "1" ? "1" : "2";
                chkInfoClsModel.FisExamine = item.FisExamine == "Y" ? "Y" : "N";

            }
            return View(chkInfoClsModel);
        }



        /// <summary>
        /// 更新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult Update() {
            Model.ChkInfoCls item = new Model.ChkInfoCls();
            item.FYear = decimal.Parse(Fetch.Post("hidyear")); //Convert.ToDecimal(Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
            item.FChkType = DropDownEditExtension.GetValue<string>("FChkType");
            item.FInfoClsName = Fetch.Post("FInfoClsName").Trim();
            item.FInfoClsNo = Fetch.Post("hidInfoClsNo").Trim();
            item.FisExamine = DropDownEditExtension.GetValue<string>("FisExamine");

            //篇数不计分
            if (DropDownEditExtension.GetValue<string>("FChkType") == "1") {
                item.FStdScore = Convert.ToDecimal(Fetch.Post("FStdScore").Trim());
            }else{
                item.FStdScore = 0;
            }

            item.FEntityNo = GlobalConstant.ENTITYNO;

            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();
            bll.Update(item);


            Response.Write("<script>alert('操作成功！');parent.location.href='" + Url.Action("Index", "ChkInfoCls") + "'</script>");
            Response.Flush();
            Response.End();



            return View("ChkInfoClsAllList");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fInfoClsNo">栏目编号</param>
        /// <returns>existsentry和existsbll表示有节点无法删除；ok表示删除成功；error系统错误删除失败</returns>
        public string DelChkInfoCls(string fInfoClsNo, string year)
        {
            fInfoClsNo = Fetch.estimateString(fInfoClsNo, CheckGetEnum.Safety);
            string str = string.Empty;
            BLL.ChkInfoCls bll = new BLL.ChkInfoCls();
            BLL.ChkInfoAuditEntry entry = new BLL.ChkInfoAuditEntry();
            //string year = Common.OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            try
            {
                if (entry.GetList("FYear='" + year + "' and FInfoClsNo='" + fInfoClsNo + "' and FEntityNo='" + GlobalConstant.ENTITYNO + "'").Tables[0].Rows.Count > 0)
                {
                    str = "existsentry";
                }
                else if (bll.GetList("FYear='" + year + "' and FPreInfoClsNo='" + fInfoClsNo + "' and FEntityNo='" + GlobalConstant.ENTITYNO + "'").Tables[0].Rows.Count > 0)
                {
                    str = "existsbll";
                }
                else
                {
                    bll.Delete(Convert.ToDecimal(year), fInfoClsNo, GlobalConstant.ENTITYNO);                   
                    str = "ok";
                }               
                
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }


    }
}
